package com.fg.pro.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.trade.dto.GmCategoryDto;
import com.fg.pro.trade.dao.TradeCategoryDao;
import com.fg.pro.trade.entity.TradeCategory;
import com.fg.pro.trade.entity.TradeGoods;
import com.fg.pro.trade.service.TradeCategoryService;
import com.fg.pro.trade.utils.GmHttpUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.fg.pro.trade.utils.GmRequestUrl.*;

/**
 * 商品分类(TradeCategory)表服务实现类
 *
 * @author makejava
 * @since 2025-08-11 14:47:29
 */
@Service("tradeCategoryService")
public class TradeCategoryServiceImpl extends ServiceImpl<TradeCategoryDao, TradeCategory> implements TradeCategoryService {

    @Autowired
    GmHttpUtils gmHttpUtils;
    @Autowired
    RedissonClient redissonClient;
    @Override
    public List<TradeCategory> getTree() {
        List<TradeCategory> list = query().eq("category_lev", 1).orderByAsc("category_sort").list();
        for (TradeCategory tradeCategory : list) {
            List<TradeCategory> children = query().eq("category_parent_id",tradeCategory.getId()).eq("category_lev", 2).orderByAsc("category_sort").list();
            tradeCategory.setChildren(children);
        }
        return list;
    }

    @Override
    public boolean refresh(Date date) throws InterruptedException {
        RLock lock = redissonClient.getLock(REDIS_LOCK_URL+GM_CATEGORY_URL);
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            return false;
        }
        try {
            return refreshTradeCategoryByLock(date);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    private boolean refreshTradeCategoryByLock(Date date) throws InterruptedException {
        GmCategoryDto.GmCategoryReponse reponse = gmHttpUtils.httpPostByToken(GM_CATEGORY_URL, new GmCategoryDto().new GmCategoryRequest(true), GmCategoryDto.GmCategoryReponse.class);
        LinkedList<TradeCategory> newList = new LinkedList<>();
        for (GmCategoryDto.GmCategoryReponse.GmCategoryData gmCategory : reponse.getCategories()) {
            TradeCategory tradeCategory = new TradeCategory();
            tradeCategory.setId(gmCategory.getCategory_id());
            tradeCategory.setCreateTime(new Date(gmCategory.getCreate_time()));
            tradeCategory.setUpdateTime(new Date(gmCategory.getUpdate_time()));
            tradeCategory.setCategoryParentId(gmCategory.getParent_id());
            tradeCategory.setCategoryName(gmCategory.getName());
            tradeCategory.setCategoryLev(gmCategory.getLevel());
            tradeCategory.setCategorySort(gmCategory.getSort_num());
            newList.add(tradeCategory);
        }
        boolean save = saveOrUpdateBatch(newList);
        return save;
    }


    @Override
    public HashMap<String, Long> getIdAndName() {
        HashMap<String, Long> map = (HashMap<String, Long>) query().list().stream().collect(Collectors.toMap(TradeCategory::getCategoryName, TradeCategory::getId));
        return map;
    }
}

